package com.elite.groovy.callback

import com.elite.groovy.kh.HttpClientProxy
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.RestTemplateService
import com.elite.groovy.util.Util
import com.wisdge.web.springframework.SpringContextUtil
import net.sf.json.JSONObject

//import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest
//import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse

import okhttp3.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
import org.springframework.util.LinkedMultiValueMap
import org.springframework.util.MultiValueMap

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

//import org.springframework.http.MediaType

//import okhttp3.MediaType.Companion.toMediaType

public class apiAutoGetU9Token implements ServiceBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(apiAutoGetU9Token.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        /*
        获取U9商品信息的token -- demi
           防止 定时任务同一时间 多次执行
           设计最大执行时间范围 开始执行后立即更新下次允许执行时间 在此期间 禁止重复执行
        1、执行频率：每日凌晨 0点
        2、根据账号和密码 获取token
        */
        String sql0 = """
            select    case when  now() >next_executedate   then  1 else 0 end  as flag from  interface_lock where interfaceName = 'apiAutoGetU9Token'
        """;
        // 查询是否有已经在执行的定时任务或者 或者之前的上次定时任务异常结束
        int flag = eliteBean.chaxun_sql(sql0, "dataSource").get(0).get("flag");

        log.debug("flag: ", flag);

        if (flag == 0) {
            log.debug(" apiAutoGetU9Token 获取U9获取商品分类列表(商品类别)： 未到下次执行时间 不予执行");
            return "success";
        } else {
            // 立即数据库标记正在执行  频率为 30s 内不重复执行
            eliteBean.update("update interface_lock set last_executedate = now(),next_executedate =STR_TO_DATE( date_add(now(), interval frequency*60 second),'%Y-%m-%d %H:%i:%s') where interfaceName = 'apiAutoGetU9Token'", "dataSource");
        };


        log.warn("---apiAutoGetU9Token 开始---");

        Date date1 = new Date();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String v_starttime = sdf.format(date1);
        log.debug(" 开始时间"+v_starttime);

        String charset = "utf-8";
        Map<String, Object> headMap = new HashMap<>(); // 请求参数头
        headMap.put("Content-Type", "application/json");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        try {

            // 获取U9商品信息的token
            String querySQL1 = "select url,string1 as  User ,string2 as  Password from sysc_interface where method='getU9Token' ";
            String url = eliteBean.chaxun_sql(querySQL1, "dataSource").get(0).get("url");
            String User = eliteBean.chaxun_sql(querySQL1, "dataSource").get(0).get("User");
            String Password = eliteBean.chaxun_sql(querySQL1, "dataSource").get(0).get("Password");

            log.debug("获取U9获取商品分类列表(商品类别)接口地址：" + url)
            log.debug("获取U9获取商品分类列表(商品类别)用户名：" + User)
            log.debug("获取U9获取商品分类列表(商品类别)密码：" + Password)
            String requestInfo = """
                {
                    "User": "${User}",
                    "Password":"${Password}"
                }
            """;

            log.debug("requestInfo: " + requestInfo);

         // String responseInfo = Util.doHttpPostUseHead(url, requestInfo, charset, 60000, 1, headMap);
            def responseInfo = Util.doHttpPostUseHead(url, requestInfo, "utf-8", 60000, 1, headMap);
            log.debug("responseInfo: " + responseInfo);
            JSONObject resJson = JSONObject.fromObject(responseInfo);

            String token = resJson.Token;
            String Expires = resJson.Expires;

            String sql = "Update sysc_interface Set  string3 = '" + token + "',string4 = '"+Expires+"'  Where method = 'getU9Token'";

            int res = eliteBean.update(sql, "dataSource");
            log.debug("更新U9token结果: " + res);


            // 执行记录
            String sql99 =  "insert into p_errorlog(v_return,v_interfanceName,v_type,v_starttime,v_endtime,v_errordesc,v_parameter1,v_parameter2)  "+
                    "values('1','apiAutoGetU9Token','1', STR_TO_DATE('"+v_starttime+"' ,'%Y/%m/%d %H:%i:%s')  ,now(),'执行成功','','') ";
            log.debug("sql99: "+sql99);
            eliteBean.update(sql99, "dataSource");


        } catch (Exception e) {


            log.error("获取U9token异常", Util.getERRO(e));

            def v_parameter2;
            def v_length= Util.getERRO(e).toString().length();
                log.debug("v_length: ",v_length);
            if( v_length>2500)  {
                v_parameter2 =Util.getERRO(e).substring(0, 2500).replace("'", "\\");
            }

            if( v_length<=2500 && v_length>0)  {
                v_parameter2 =Util.getERRO(e).substring(0, v_length-1).replace("'", "\\");
            }
            // 执行记录
            String sql99 =  "insert into p_errorlog(v_return,v_interfanceName,v_type,v_starttime,v_endtime,v_errordesc,v_parameter1,v_parameter2)  "+
                    "values('-1','apiAutoGetU9Token','1',STR_TO_DATE('"+v_starttime +"', '%Y/%m/%d %H:%i:%s') ,now(),'接口异常','','"+v_parameter2+"')";
            log.debug("sql99: "+sql99);
            eliteBean.update(sql99, "dataSource");

        };

        log.debug("获取U9token  耗时：" + ((long) new Date().getTime() - (long) date1.getTime()) + "毫秒");
        return "success";

    };

}
